package cn.edu.cqvie.ssm.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import lombok.Builder;
import lombok.Data;

/**
 * 数据库连接处理类，包括获取连接，关闭连接等处理
 * @author zhengsh
 */
@Data
@Builder
public class Dbconn {

	
	/**
	 * 获取数据库连接
	 */
	public Connection getConnection() throws ClassNotFoundException, SQLException {
		//1、注册MySQL驱动
		Class.forName("com.mysql.jdbc.Driver");
		//2、获取数据库连接
		Connection con = DriverManager.getConnection(
				"jdbc:mysql://127.0.0.1:3306/mydatabase?useUnicode=true&characterEncoding=utf8&useSSL=true", 
				"root", 
				"root123");
		return con;
	}
	
	public void closeAll(Connection con, PreparedStatement ps, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
			if (con !=null) {
				con.close();
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
	
	public void closeAll(Connection con, Statement st, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (st != null) {
				st.close();
			}
			if (con !=null) {
				con.close();
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}

	}
	
	
	public static void close(Connection con, PreparedStatement ps, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
			if (con !=null) {
				con.close();
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
	
	public static void close(Connection con, Statement st, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (st != null) {
				st.close();
			}
			if (con !=null) {
				con.close();
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}

	}
	
//	public static void main(String[] args) {
//		try {
//			
//			//3、创建Statement对象
//			Statement st = con.createStatement();  
//			//4、执行SQL
//			ResultSet rs = st.executeQuery("select * from user");
//			//5、打印结果
//			while (rs.next()) {
//				System.out.println("name=" + rs.getString("name") + " password=" + rs.getString("password") );
//			}
//			//6、关闭连接
//		
//		} catch (Throwable e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}
}
